import { useState, useEffect } from "react";

const useKeyPress = (targetCode) => {
  const [keyPressed, setKeyPressed] = useState(false);

  const handleKeyDown = (e) => {
    if (e.keyCode === targetCode) {
      setKeyPressed(true);
    }
  };
  const handleKeyUp = (e) => {
    if (e.keyCode === targetCode) {
      setKeyPressed(false);
    }
  };
  
  useEffect(() => {
    window.addEventListener("keydown", handleKeyDown);
    window.addEventListener("keyup", handleKeyUp);

    return () => {
      window.removeEventListener("keydown", handleKeyDown);
      window.removeEventListener("keyup", handleKeyUp);
    };
  });  

  return keyPressed;
};

export default useKeyPress;
